#!/bin/bash
# Wrapper script to generate Dumbo_NG keys

# 脚本失败时立即退出
set -e 

# --- 从环境变量或默认值获取参数 ---
# Fabric 任务在调用此脚本时需要设置这些环境变量
CONFIG_DIR=${FABRIC_CONFIG_PATH:-"/home/ubuntu/Dumbo_NG/config"}
NODES=${FABRIC_NODES:-4}
PROJECT_DIR=${FABRIC_PROJECT_PATH:-"/home/ubuntu/Dumbo_NG"} 
# 计算阈值 T
FAULT_TOLERANCE=$(( NODES / 2 )) # f = floor(N/2), e.g., N=4 -> f=2? Or N=4, f=1? Dumbo needs N >= 3f+1. If N=4, max f=1. T=f+1.
T=$(( FAULT_TOLERANCE + 1 )) # T = f + 1. For N=4, f=1, T=2. 
# ！！！请根据 Dumbo_NG 的实际要求确认 T 的计算方式！！！ 
# 如果 T 应该是 floor(N/2)+1, 则 T=$(( NODES / 2 + 1 ))

KEYS_DIR="${CONFIG_DIR}/keys"
THRESH_DIR="${CONFIG_DIR}/threshold_keys"

echo "--- [Wrapper Script] 开始执行 ---"
echo "Config Dir: ${CONFIG_DIR}"
echo "Nodes: ${NODES}"
echo "Project Dir: ${PROJECT_DIR}"
echo "Keys Dir: ${KEYS_DIR}"
echo "Thresh Dir: ${THRESH_DIR}"
echo "Calculated Threshold T: ${T} (for N=${NODES})"

# 确保目录存在
mkdir -p "${KEYS_DIR}"
mkdir -p "${THRESH_DIR}"

# 清理旧密钥文件
echo "Cleaning old keys..."
rm -f "${KEYS_DIR}"/*
rm -f "${THRESH_DIR}"/*

# 进入项目目录 (因为要执行 ./dumbo_ng)
cd "${PROJECT_DIR}"

# 执行 keys 命令
echo "Generating node keys..."
# 将 stdout/stderr 重定向到临时文件以便调试
./dumbo_ng keys --path "${KEYS_DIR}" --nodes "${NODES}" > /tmp/keys_stdout.log 2> /tmp/keys_stderr.log
echo "'keys' command exited with status $?"
echo "--- keys stdout ---"
cat /tmp/keys_stdout.log
echo "--- keys stderr ---"
cat /tmp/keys_stderr.log
rm -f /tmp/keys_stdout.log /tmp/keys_stderr.log

# 检查文件是否生成
echo "Checking node keys..."
if ! ls -l "${KEYS_DIR}" | grep -q '.node-key-0.json'; then
    echo "ERROR: Node keys not found after generation!"
    ls -l "${KEYS_DIR}" # 显示目录内容以供调试
    exit 1
fi

# 执行 threshold_keys 命令
echo "Generating threshold keys..."
./dumbo_ng threshold_keys --path "${THRESH_DIR}}" --N "${NODES}}" --T "${T}" > /tmp/thresh_stdout.log 2> /tmp/thresh_stderr.log
echo "'threshold_keys' command exited with status $?"
echo "--- threshold_keys stdout ---"
cat /tmp/thresh_stdout.log
echo "--- threshold_keys stderr ---"
cat /tmp/thresh_stderr.log
rm -f /tmp/thresh_stdout.log /tmp/thresh_stderr.log

# 检查文件是否生成
echo "Checking threshold keys..."
if ! ls -l "${THRESH_DIR}" | grep -q '.node-ts-key-0.json'; then
    echo "ERROR: Threshold keys not found after generation!"
    ls -l "${THRESH_DIR}" # 显示目录内容以供调试
    exit 1
fi

# 修改权限
echo "Changing permissions..."
chmod 644 "${KEYS_DIR}"/*
chmod 644 "${THRESH_DIR}"/*

echo "--- [Wrapper Script] 成功完成 ---"
exit 0